<?php

$userid = get_loggedin_userid();
//$userid = get_input('userid');
$device_token = get_input('device_token');

if(strlen($device_token) > 10) {

	// solve temporality
	$delete_device_token_sql = "DELETE FROM users_device_info WHERE userid = $userid";
	
	try {
		delete_data($delete_device_token_sql);
	} catch(DatabaseException $dbe) {
		die(json_encode(export_result(400, array())));
	}

	// check device token is exist
	$get_device_token_sql = "SELECT count(*) as total FROM users_device_info WHERE device_token = '$device_token'";
	try {
		$results = get_data($get_device_token_sql);
		
		$total_record = 0;
		foreach($results as $result) {
			$total_record = intval($result->total);
		}
		
		// device token not yet exist => add new
		if($total_record == 0) {
			$insert_new_device_token_sql = "INSERT INTO users_device_info(userid, device_token, created_time) VALUES($userid, '$device_token', ".time().")";
			try {
				insert_data($insert_new_device_token_sql);
			} catch(DatabaseException $dbe) {
				die(json_encode(export_result(400, array())));
			}
		} else { // update token
			$update_device_token_sql = "UPDATE users_device_info SET userid = '$userid', created_time = ".time()." WHERE device_token = '$device_token'";
			try {
				update_data($update_device_token_sql);
			} catch(DatabaseException $dbe) {
				die(json_encode(export_result(400, array())));
			}
		}
		
	} catch(DatabaseException $dbe) {
		die(json_encode(export_result(400, array())));
	}
	


}

// default return
$return = array(
				'userid' => $userid,
				'device_token' => $device_token
			);

echo json_encode(export_result(200, $return));

?>